<template>
  <div class="todo-container">
    <el-row justify="center">
      <el-col :xs="24" :sm="20" :md="16" :lg="14" :xl="12">
        <!-- 添加新任务 -->
        <div class="button-container">
          <el-button type="primary" :size="isMobile ? 'large' : 'default'" @click="showAddDialog">
            <el-icon class="el-icon--left"><Plus /></el-icon>
            添加待办事项
          </el-button>
        </div>

        <!-- 任务列表卡片 -->
        <el-card class="todo-list" :body-style="{ padding: isMobile ? '10px' : '20px' }">
          <template #header>
            <div class="card-header">
              <span>任务列表</span>
              <el-radio-group v-model="filter" :size="isMobile ? 'large' : 'default'" class="filter-group">
                <el-radio-button label="all">全部</el-radio-button>
                <el-radio-button label="active">进行中</el-radio-button>
                <el-radio-button label="completed">已完成</el-radio-button>
              </el-radio-group>
            </div>
          </template>

          <el-empty v-if="filteredTodos.length === 0" description="暂无待办事项" />

          <el-table 
            v-else
            :data="filteredTodos" 
            style="width: 100%"
            :size="isMobile ? 'large' : 'default'"
          >
            <!-- 展开列 -->
            <el-table-column type="expand">
              <template #default="props">
                <div class="todo-expand">
                  <p class="expand-item">
                    <span class="label">描述：</span>
                    <span>{{ props.row.description || '暂无描述' }}</span>
                  </p>
                  <p class="expand-item">
                    <span class="label">优先级：</span>
                    <el-tag :type="props.row.priority === 'high' ? 'danger' : props.row.priority === 'medium' ? 'warning' : 'info'" size="small">
                      {{ props.row.priority_display }}
                    </el-tag>
                  </p>
                  <p class="expand-item">
                    <span class="label">状态：</span>
                    <el-tag :type="props.row.status === 'completed' ? 'success' : 'warning'" size="small">
                      {{ props.row.status_display }}
                    </el-tag>
                  </p>
                  <p class="expand-item">
                    <span class="label">截止日期：</span>
                    <span>{{ props.row.due_date || '未设置' }}</span>
                  </p>
                </div>
              </template>
            </el-table-column>

            <!-- 标题列 -->
            <el-table-column label="标题" min-width="200">
              <template #default="scope">
                <span :class="{ completed: scope.row.status === 'completed' }">{{ scope.row.title }}</span>
              </template>
            </el-table-column>

            <!-- 操作列 -->
            <el-table-column align="right" width="150">
              <template #default="scope">
                <el-button
                  type="primary"
                  :size="isMobile ? 'large' : 'small'"
                  @click="editTodo(scope.row)"
                >
                  <el-icon><Edit /></el-icon>
                </el-button>
                <el-button
                  type="danger"
                  :size="isMobile ? 'large' : 'small'"
                  @click="deleteTodo(scope.row)"
                >
                  <el-icon><Delete /></el-icon>
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <div v-if="todos.length > 0" class="todo-footer">
            <span>{{ activeCount }} 项待完成</span>
            <el-button v-if="completedCount > 0" type="danger" :size="isMobile ? 'large' : 'small'" @click="clearCompleted">
              清除已完成
            </el-button>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 编辑对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      :title="isEdit ? '编辑待办事项' : '添加待办事项'"
      :width="isMobile ? '95%' : '30%'"
      :close-on-click-modal="false"
    >
      <el-form :model="editForm" label-width="80px" :size="isMobile ? 'large' : 'default'">
        <el-form-item label="标题">
          <el-input v-model="editForm.title" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="editForm.description" type="textarea" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="editForm.status">
            <el-option label="待办" value="pending" />
            <el-option label="完成" value="completed" />
          </el-select>
        </el-form-item>
        <el-form-item label="优先级">
          <el-select v-model="editForm.priority">
            <el-option label="低" value="low" />
            <el-option label="中" value="medium" />
            <el-option label="高" value="high" />
          </el-select>
        </el-form-item>
        <el-form-item label="截止日期">
          <el-date-picker v-model="editForm.due_date" type="date" value-format="YYYY-MM-DD" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button :size="isMobile ? 'large' : 'default'" @click="editDialogVisible = false">取消</el-button>
          <el-button :size="isMobile ? 'large' : 'default'" type="primary" @click="saveEdit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { Delete, Edit, Plus } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { getTodoList, createTodo, updateTodo, deleteTodo as deleteTodoApi } from '@/api/todo'

const newTodo = ref('')
const filter = ref('all')
const todos = ref([])
const loading = ref(false)
const editDialogVisible = ref(false)
const isEdit = ref(false)
const editForm = ref({
  id: null,
  title: '',
  description: '',
  status: 'pending',
  priority: 'medium',
  due_date: null
})

// 根据筛选条件显示待办事项
const filteredTodos = computed(() => {
  switch (filter.value) {
    case 'active':
      return todos.value.filter(todo => todo.status === 'pending')
    case 'completed':
      return todos.value.filter(todo => todo.status === 'completed')
    default:
      return todos.value
  }
})

// 统计数量
const activeCount = computed(() => todos.value.filter(todo => todo.status === 'pending').length)
const completedCount = computed(() => todos.value.filter(todo => todo.status === 'completed').length)

// 获取待办事项列表
const fetchTodos = async () => {
  loading.value = true
  try {
    const response = await getTodoList()
    todos.value = response.results || response
  } catch (error) {
    ElMessage.error('获取待办事项失败')
  } finally {
    loading.value = false
  }
}

// 初始化时获取数据
onMounted(() => {
  fetchTodos()
})

// 添加移动端判断
const isMobile = computed(() => window.innerWidth <= 768)

// 显示添加对话框
const showAddDialog = () => {
  isEdit.value = false
  editForm.value = {
    id: null,
    title: '',
    description: '',
    status: 'pending',
    priority: 'medium',
    due_date: null
  }
  editDialogVisible.value = true
}

// 显示编辑对话框
const editTodo = (todo) => {
  isEdit.value = true
  editForm.value = { ...todo }
  editDialogVisible.value = true
}

// 保存编辑
const saveEdit = async () => {
  if (!editForm.value.title.trim()) {
    ElMessage.warning('标题不能为空')
    return
  }

  loading.value = true
  try {
    if (isEdit.value) {
      await updateTodo(editForm.value.id, editForm.value)
      ElMessage.success('修改成功')
    } else {
      await createTodo(editForm.value)
      ElMessage.success('添加成功')
    }
    editDialogVisible.value = false
    await fetchTodos()
  } catch (error) {
    ElMessage.error(isEdit.value ? '修改失败' : '添加失败')
  } finally {
    loading.value = false
  }
}

// 删除待办事项
const deleteTodo = async (todo) => {
  loading.value = true
  try {
    await deleteTodoApi(todo.id)
    ElMessage.success('删除成功')
    await fetchTodos()
  } catch (error) {
    ElMessage.error('删除失败')
  } finally {
    loading.value = false
  }
}

// 清除已完成的待办事项
const clearCompleted = () => {
  todos.value = todos.value.filter(todo => todo.status === 'pending')
  ElMessage.success('清除成功')
}
</script>

<style scoped>
.todo-container {
  padding: 20px;
  margin-top: 60px;
  max-width: 1400px;
  margin-left: auto;
  margin-right: auto;
}

.button-container {
  margin-bottom: 20px;
  display: flex;
  justify-content: flex-end;
}

.button-container .el-button {
  min-width: 120px;
}

@media (max-width: 768px) {
  .button-container {
    justify-content: center;
  }

  .button-container .el-button {
    width: 100%;
    max-width: 200px;
  }
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
}

.filter-group {
  width: 100%;
  display: flex;
}

.filter-group :deep(.el-radio-button) {
  flex: 1;
}

.filter-group :deep(.el-radio-button__inner) {
  width: 100%;
}

.todo-expand {
  padding: 20px;
}

.expand-item {
  margin-bottom: 10px;
  display: flex;
  align-items: center;
}

.expand-item:last-child {
  margin-bottom: 0;
}

.expand-item .label {
  font-weight: bold;
  margin-right: 10px;
  min-width: 70px;
}

.el-table {
  --el-table-border-color: var(--el-border-color-lighter);
  border: 1px solid var(--el-table-border-color);
  border-radius: 4px;
}

.todo-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #eee;
  flex-wrap: wrap;
  gap: 10px;
}

.completed {
  text-decoration: line-through;
  color: #999;
}

.todo-actions {
  display: flex;
  gap: 8px;
}
</style>
